'''
Created on Apr 19, 2009

@author: Administrator
'''
import datetime
from django.utils.translation import ugettext_lazy as _
from com.ericyang.groupshopping.product.models import Category, Product, CATEGORY_TOP_LEVEL
from django import forms
from com.ericyang.common import file as file_tool
from com.ericyang.common.web.middleware import threadlocals
from settings import BASE_UPLOAD_DIR as upload_dir

# product creation form
class ProductCreationForm(forms.ModelForm):
    '''
    form of product creation
    '''
    name = forms.CharField(label=_("name"), max_length=50)
    marketPrice = forms.DecimalField(label=_("market Price"), max_digits=12, decimal_places=2)
    image = forms.Field(label=_("image Path"), widget=forms.FileInput)
    introducation = forms.CharField(label=_("introducation"), max_length=2000, widget=forms.Textarea)
    category_id = forms.ChoiceField(label=_("super category"), choices=())
    
    class Meta:
         model = Product
         fields = ("name", 'marketPrice', 'introducation', 'category_id')
         
    def __init__(self, *args, **kwargs):
        self.base_fields['category_id'].choices = [(cate.id, cate.name) for cate in Category.objects.filter(level=CATEGORY_TOP_LEVEL)]
        super(ProductCreationForm, self).__init__(*args, **kwargs)

    def save(self, commit=True):
        product = super(ProductCreationForm, self).save(commit=False)
        category_id = self.cleaned_data['category_id']
        if category_id:
            category = Category.objects.get(pk=category_id)
        else:
            category = None
        product.category = category
        image = self.cleaned_data['image']
        file_path = file_tool.save_file(upload_dir, image)
        product.imagePath = file_path
        product.user = threadlocals.get_current_user()
        product.create_time = datetime.datetime.now()
        
        if commit:
            product.save()
        return product

# product creation form
class ProductChangeForm(forms.ModelForm):
    '''
    form of product creation
    '''
    name = forms.CharField(label=_("name"), max_length=50)
    marketPrice = forms.DecimalField(label=_("market Price"))
    imagePath = forms.CharField(label=_("image Path"), max_length=255)
    introducation = forms.CharField(label=_("introducation"), max_length=2000, widget=forms.Textarea)
    category_id = forms.ChoiceField(label=_("super category"), choices=())
    
    class Meta:
         model = Product
         fields = ("name", 'marketPrice', 'imagePath', 'introducation', 'category_id')
         
    def __init__(self, product, *args, **kwargs):
        self.base_fields['category_id'].choices = [(cate.id, cate.name) for cate in Category.objects.filter(level=CATEGORY_TOP_LEVEL)]
        self.product = product
        
        # if not args then it's not POST.
        if not args:
            product_args = {'name':product.name,
                            'marketPrice':product.marketPrice,
                            'introducation':product.introducation,
                            'imagePath':product.imagePath,
                            'category_id':product.category.id, }
            super(ProductChangeForm, self).__init__(product_args, **kwargs)
        else:
            super(ProductChangeForm, self).__init__(*args, **kwargs)

    def save(self, commit=True):
        category_id = self.cleaned_data['category_id']
        if category_id:
            category = Category.objects.get(pk=category_id)
        else:
            category = None
        self.product.category = category    
        
        if commit:
            self.product.save()
        return self.product
    
# category ModelChoiceField
class CategoryModelChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, category):
        return category.name


# category creation form
class CategoryCreationForm(forms.ModelForm):
    '''
    form of category creation
    '''
    name = forms.CharField(label=_("category name"), max_length=50)
    url = forms.CharField(label=_("category url"), max_length=255, required=False)
    category_id = forms.ChoiceField(label=_("super category"), choices=(), required=False)
    
    class Meta:
         model = Category
         fields = ("name", 'category_id','url')
         
    def __init__(self, level, *args, **kwargs):
        self.level = level
        self.base_fields['category_id'].choices = [(cate.id, cate.name) for cate in Category.objects.filter(level=int(level) - 1)]
        super(CategoryCreationForm, self).__init__(*args, **kwargs)

    def save(self, commit=True):
        category = super(CategoryCreationForm, self).save(commit=False)
        
        category_id = self.cleaned_data['category_id']
        if category_id:
            super_category = Category.objects.get(pk=category_id)
        else:
            super_category = None
        category.super_category = super_category    
        
        category.level = category.get_level()
        if commit:
            category.save()
        return category
    
class CategoryChangeForm(forms.Form):
    '''
    form of category change
    '''
    name = forms.CharField(label=_("category name"), max_length=50)
    url = forms.CharField(label=_("category url"), max_length=255, required=False)
    category_id = forms.ChoiceField(label=_("super category"), choices=(), required=False)
    
    class Meta:
         model = Category
         fields = ("name", 'category_id','url')
    
    def __init__(self, category, *args, **kwargs):
        self.category = category
        
        self.base_fields['category_id'].choices = [(cate.id, cate.name) for cate in Category.objects.filter(level__lt=category.level)]
        
        # if not args then it's not POST.
        if not args:
            category_arg = {'name':category.name,"url":category.url}
            if category.super_category:
                category_arg.update({'category_id':category.super_category.id})
            super(CategoryChangeForm, self).__init__(category_arg, **kwargs)
        else:
            super(CategoryChangeForm, self).__init__(*args, **kwargs)


    def save(self, commit=True):
        category_id = self.cleaned_data['category_id']
        if category_id:
            super_category = Category.objects.get(pk=category_id)
        else:
            super_category = None
        self.category.name = self.cleaned_data['name']
        self.category.url = self.cleaned_data['url']
        self.category.super_category = super_category        
        self.category.level = self.category.get_level()
        if commit:
            self.category.save()
        return self.category



